import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * 
 * @author "Cunxin Jia"
 *
 */
public class Atom {
	private String predicate;
	private List<Term> terms;
	
	public Atom(String atomString) {
		int lbpos = atomString.indexOf('(');
		int rbpos = atomString.indexOf(')');
		predicate = atomString.substring(0, lbpos);
		String termsString = atomString.substring(lbpos + 1, rbpos);
		Scanner input = new Scanner(termsString);
		terms = new ArrayList<Term>();
		input.useDelimiter(",");
		while(input.hasNext()) {
			String curTerm = input.next().trim();
			terms.add(new Term(curTerm));
		}
	}
	
	public Atom(String predicate, List<Term> terms) {
		this.predicate = predicate;
		this.terms = terms;
	}
	
	public String getPredicate() {
		return predicate;
	}
	
	public List<Term> getTerms() {
		return terms;
	}
	
	public int getNumOfVars() {
		int numOfVars = 0;
		for(int i = 0; i < terms.size(); i++) {
			if(!terms.get(i).isConstant()) {
				numOfVars++;
			}
		}
		return numOfVars;
	}
	
	public String toString() {
		String atomString = predicate + "(";
		for(int i = 0; i < terms.size() - 1; i++) {
			atomString += terms.get(i).getVar() + ",";
		}
		atomString += terms.get(terms.size() - 1).getVar() + ")";
		return atomString;
	}
	
	public void substitute(int index, Term newTerm) {
		terms.set(index, newTerm);
	}
}
